<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col
            :md="4"
            :sm="12">
            <a-form-item label="使用状态">
              <a-select
                v-model="queryParam.status"
                placeholder="请选择"
                default-value="0">
                <a-select-option value="-1">全部</a-select-option>
                <a-select-option value="1">激活</a-select-option>
                <a-select-option value="2">禁用</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col
            :md="4"
            :sm="24">
            <a-form-item label="用户名">
              <a-input
                v-model="queryParam.name"
                placeholder="请输入搜索关键字" />
            </a-form-item>
          </a-col>
          <a-col
            :md="4"
            :sm="24">
            <a-form-item label="邮箱">
              <a-input
                v-model="queryParam.email"
                placeholder="请输入搜索关键字" />
            </a-form-item>
          </a-col>
          <a-col
            :md="4"
            :sm="24">
            <span
              class="table-page-search-submitButtons"
              :style="{ float: 'right', overflow: 'hidden' }">
              <a-button
                type="primary"
                @click="$refs.table.refresh(true)">查询</a-button>
              <a-button
                style="margin-left: 8px"
                @click="queryParam = {};$refs.table.refresh(true);">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <div class="table-operator">
      <a-button
        v-if="$auth('admin.sys-user.save')"
        type="primary"
        icon="plus"
        @click="$refs.createModal.add()">新建</a-button>
    </div>

    <s-table
      ref="table"
      size="default"
      rowKey="id"
      :columns="columns"
      :data="loadData"
      showPagination="auto">
      <span
        slot="avatar"
        slot-scope="text">
        <a-avatar
          size="large"
          icon="user"
          :src="text" />
      </span>
      <span
        slot="roles"
        slot-scope="text">
        <a-tag
          color="#2db7f5"
          v-for="(item, key) in text"
          :key="key">{{ item.label }}</a-tag>
      </span>
      <span
        slot="status"
        slot-scope="text, record">
        <a-tag :color="record.deleted_at ? '#f50' : '#87d068'">{{ record.deleted_at ? '禁用' : '激活' }}</a-tag>
      </span>
      <span
        slot="action"
        slot-scope="text, record">
        <template>
          <a-button
            size="small"
            icon="edit"
            type="primary"
            v-if="$auth('admin.sys-user.save')"
            @click="$refs.createModal.edit(record)">编辑</a-button>
          <a-divider
            v-if="$auth('admin.sys-user.changestatus')"
            type="vertical" />
          <a-button
            size="small"
            icon="edit"
            :type="record.deleted_at ? 'primary' : 'danger'"
            v-if="record.deleted_at ? $auth('admin.sys-user.enable') : $auth('admin.sys-user.disable')"
            @click="handleChangeStatus(record)">{{ record.deleted_at ? '激活' : '禁用' }}</a-button>
        </template>
      </span>
    </s-table>
    <create-form
      ref="createModal"
      :roleList="roleList"
      @ok="$refs.table.refresh()" />
  </a-card>
</template>

<script>
import moment from 'moment'
import { STable } from '@/components'
import CreateForm from './modules/SysUserCreateForm'
import { loadList, disable, enable } from '@/api/system/sysuser'
// 角色树结构数据转换
const roleFormatter = (list) => {
  if (list === null) return []
  const re = list.map(
    (item) => {
      const result = {
        children: [],
        value: item.role_id,
        title: item.display_name,
        parent_id: item.parent_id
      }
      if (item.children != null) {
        result.children = roleFormatter(item.children)
      }
      return result
    }
  )
  return re
}
export default {
  name: 'SysUser',
  components: {
    STable,
    CreateForm
  },
  data () {
    return {
      mdl: {},
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: 'id'
        },
        {
          title: '用户名称',
          dataIndex: 'name'
        },
        {
          title: '用户头像',
          dataIndex: 'avatar',
          scopedSlots: { customRender: 'avatar' }
        },
        {
          title: '邮箱',
          dataIndex: 'email'
        },
        {
          title: '角色',
          dataIndex: 'role_ids',
          scopedSlots: { customRender: 'roles' }
        },
        {
          title: '状态',
          dataIndex: 'status',
          scopedSlots: { customRender: 'status' }
        },
        {
          title: '创建时间',
          dataIndex: 'created_at'
        },
        {
          title: '操作',
          dataIndex: 'action',
          fixed: 'right',
          scopedSlots: { customRender: 'action' }
        }
      ],
      roleList: []
    }
  },
  filters: {},
  created () {
  },
  methods: {
    // 加载数据方法 必须为 Promise 对象
    loadData (parameter) {
      console.log('loadData.parameter', parameter)
      return loadList(Object.assign(parameter, this.queryParam))
        .then(res => {
          this.roleList = roleFormatter(res.data.roleList)
          return {
            pageNo: res?.data?.pageNo || 1,
            totalCount: res?.data?.total || 0,
            data: res?.data?.userList || []
            }
        })
    },
    handleChangeStatus (record) {
      const actionName = record.deleted_at ? '激活' : '禁用'
      const actionStatus = record.deleted_at ? 1 : 0
      this.$confirm({
        title: '你确定要该' + actionName + '用户？',
        content: '此操作将' + actionName + '该用户, 是否继续?',
        onOk: () => {
          if (actionStatus === 1) {
            return enable([record.id]).then(res => {
              if (res.code === 0) {
                this.$refs.table.refresh()
                this.$message.success(
                  actionName + '用户成功'
                )
              }
            }).catch((error) => console.error(error))
          } else {
            return disable([record.id]).then(res => {
            if (res.code === 0) {
              this.$refs.table.refresh()
              this.$message.success(
                actionName + '用户成功'
              )
            }
          }).catch((error) => console.error(error))
          }
        },
        onCancel () {
        }
      })
    },
    resetSearchForm () {
      this.queryParam = {
        date: moment(new Date())
      }
    }
  }
}
</script>
